#!/bin/bash

# 数据库连接测试脚本

DB_HOST="rm-bp1nv0zakj96v24k7vo.mysql.rds.aliyuncs.com"
DB_PORT="3306"
DB_NAME="news"
DB_USER="news_db"
DB_PASS="Aa270141577!"

echo "Testing database connection..."
echo "Host: $DB_HOST:$DB_PORT"
echo "Database: $DB_NAME"
echo "Username: $DB_USER"
echo ""

# 测试网络连接
echo "1. Testing network connectivity..."
if timeout 5 bash -c "</dev/tcp/$DB_HOST/$DB_PORT"; then
    echo "✅ Network connection successful"
else
    echo "❌ Cannot connect to $DB_HOST:$DB_PORT"
    echo "Please check:"
    echo "- Network connectivity"
    echo "- Firewall settings"
    echo "- Database server status"
    exit 1
fi

echo ""

# 测试MySQL连接（如果有mysql客户端）
echo "2. Testing MySQL authentication..."
if command -v mysql > /dev/null 2>&1; then
    if mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -D "$DB_NAME" -e "SELECT 1;" > /dev/null 2>&1; then
        echo "✅ MySQL authentication successful"
        echo "✅ Database '$DB_NAME' accessible"
    else
        echo "❌ MySQL authentication failed"
        echo "Please check:"
        echo "- Username: $DB_USER"
        echo "- Password: [HIDDEN]"
        echo "- Database name: $DB_NAME"
        echo "- User permissions"
    fi
else
    echo "⚠️  MySQL client not found, skipping authentication test"
    echo "Install mysql client: apt-get install mysql-client (Ubuntu) or brew install mysql (Mac)"
fi

echo ""

# 显示JDBC URL
echo "3. JDBC Connection String:"
echo "jdbc:mysql://$DB_HOST:$DB_PORT/$DB_NAME?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"

echo ""
echo "If network connection is OK but authentication fails,"
echo "please verify your database credentials with your DBA."